package br.org.acessobrasil.portal.persistencia;

import java.util.List;
import java.util.Random;

import javax.persistence.Query;

import br.org.acessobrasil.portal.modelo.NewsDestinatario;

public class NewsDestinatarioDao extends SuperDao<NewsDestinatario>{

	@Override
	public NewsDestinatario select(Long id) {
		return getEntityManager().find(NewsDestinatario.class,id);
	}
	public NewsDestinatario select(String cod_remocao) {
		NewsDestinatario res=null;
		Query q = getEntityManager().createQuery("Select d From NewsDestinatario d where d.cod_remocao=?");
		q.setParameter(1, cod_remocao);
		try{
			res = (NewsDestinatario)q.getSingleResult();
		}catch(Exception e){
			//may not found
		}
		return res;
	}
	/**
	 * Verifica se existe um usu&aacute;rio com o mesmo e-mail
	 * Aten&ccedil;&atilde;o: ele cria automaticamente o c&oacute;digo de remo&ccedil;&atilde;o 
	 * @throws Exception 
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void create(NewsDestinatario obj) throws Exception {
		//verifica se existe email igual, deve ser unique
		Query q = getEntityManager().createQuery("Select d From NewsDestinatario d where d.email=?");
		q.setParameter(1,obj.getEmail());
		if(q.getResultList().size()>0){
			List<NewsDestinatario> list = q.getResultList();
			System.out.println(list.get(0).getNome());
			//existe
			return;
		}
		//cod_remocao deve ser unique, e auto generated
		String cod_remocao;
		do{
			cod_remocao="";
			Random rd = new Random();
			for(int i=0;i<20;i++){
				cod_remocao+=(char)(65+rd.nextInt(23));
			}
		}while(select(cod_remocao)!=null);
		obj.setCodRemocao(cod_remocao);
		super.create(obj);
	}
	public void delete(NewsDestinatario obj){
		if(obj.getNuNewsDestinatario()!=null){
			obj = select(obj.getNuNewsDestinatario());
			getEntityManager().remove(obj);
		}else{
			if(obj.getCodRemocao()!=null){
				delete(obj.getCodRemocao());
			}
		}
	}
	public void delete(String cod_remocao){
		NewsDestinatario obj = select(cod_remocao);
		if(obj!=null) getEntityManager().remove(obj);
	}
	@SuppressWarnings("unchecked")
	public List<NewsDestinatario> list() {
		return getEntityManager().createQuery("Select d From NewsDestinatario d order by d.nome").getResultList();
	}
}
